package com.dcrzl.gazgmh.module.sys.controller;

import com.dcrzl.gazgmh.common.annotation.SysLog;
import com.dcrzl.gazgmh.common.dto.LoginDto;
import com.dcrzl.gazgmh.common.entity.sys.SysConfig;
import com.dcrzl.gazgmh.common.entity.sys.SysUser;
import com.dcrzl.gazgmh.common.utils.*;
import com.dcrzl.gazgmh.module.common.service.CaptchaService;
import com.dcrzl.gazgmh.module.sys.service.SysConfigService;
import com.dcrzl.gazgmh.module.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author dcrzl
 * @email 1728795786@qq.com
 * @date 2023-04-25 13:39:00
 */
@Slf4j
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户登录
     *
     * @return
     */
    @SysLog(value = "用户登录", type = 0)
    @PostMapping("/login")
    public Result<Object> login(@RequestBody LoginDto loginDto) {
        Result<SysConfig> sysConfigResult = sysConfigService.selectOne(new SysConfig().setStatus(SysConstant.DATA_NORMAL_STATUS));
        int errorTime = 5;
        if (sysConfigResult.isSuccess()) {
            SysConfig sysConfig = sysConfigResult.getData();
            errorTime = sysConfig.getErrorTime();
        }
        String s = stringRedisTemplate.opsForValue().get(loginDto.getLoginName() + ":error");
        if (StringUtils.hasText(s)) {
            int i = Integer.parseInt(s);
            if (i >= errorTime) {
                log.info(errorTime + "");
                return new Result<>().setSuccess(false).setMsg("登录错误次数超过" + errorTime + "次,请10分钟之后重试");
            }
        } else {
            s = "0";
        }
        log.info(s);
        //验证图形验证码
        Result validate = captchaService.validate(loginDto.getUuid(), loginDto.getCaptcha());
        if (validate.isSuccess()) {
            String password = loginDto.getPassword();
            String loginName = loginDto.getLoginName();
            SysUser sysUser = new SysUser();
            password = EncryptionUtil.getEncryption("md5", password);
            sysUser.setPassword(password);
            //识别登录名是手机号还是用户名
            if (SysUtils.checkChinaPhoneLegal(loginName)) {
                sysUser.setPhone(loginName);
            } else if (SysUtils.checkEmail(loginName)) {
                sysUser.setMail(loginName);
            } else {
                sysUser.setUsername(loginName);
            }
            validate = sysUserService.login(sysUser);
        }
        if (!validate.isSuccess()) {
            log.info(Integer.parseInt(s) + 1 + "");
            stringRedisTemplate.opsForValue().set(loginDto.getLoginName() + ":error", Integer.parseInt(s) + 1 + "", 10, TimeUnit.MINUTES);
        } else {
            //清除登录错误记录
            stringRedisTemplate.delete(loginDto.getLoginName() + ":error");
        }
        return validate;
    }


    /**
     * 列表分页
     */
    @GetMapping("/page")
    public PageInfo<SysUser> page(SysUser sysUser) {
        return sysUserService.selectURolePage(sysUser);
    }

    /**
     * 信息
     */
    @GetMapping("/info")
    public Result<SysUser> info(SysUser sysUser) {
        sysUser.setId(this.getUserId());
        return sysUserService.selectOne(sysUser);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public Result<SysUser> info(@PathVariable("id") Long id) {
        return sysUserService.selectById(id);
    }

    /**
     * 保存
     */
    @SysLog(value = "保存用户")
    @PostMapping("/save")
    public Result<Integer> save(@RequestBody SysUser sysUser) {
        sysUser.setUserCode("U" + System.currentTimeMillis());
        sysUser.setPassword(EncryptionUtil.getEncryption("md5", sysUser.getPassword()));
        Result<SysConfig> sysConfigResult = sysConfigService.selectOne(new SysConfig().setStatus(SysConstant.DATA_NORMAL_STATUS));
        if (sysConfigResult.isSuccess()) {
            SysConfig sysConfig = sysConfigResult.getData();
            Integer passwordValidDay = sysConfig.getPasswordValidDay();
            Date date = SysUtils.dateAddDay(new Date(), passwordValidDay);
            sysUser.setPasswordExpireDate(date);
        }
        return sysUserService.insert(sysUser);
    }

    /**
     * 修改
     */
    @SysLog(value = "修改用户")
    @PutMapping("/update")
    public Result<Integer> update(@RequestBody SysUser sysUser) {
        return sysUserService.updateById(sysUser);
    }

    /**
     * 修改
     */
    @SysLog(value = "修改用户密码")
    @PutMapping("/update/password")
    public Result<Integer> updatePassword(@RequestBody SysUser sysUser) {
        if (StringUtils.hasText(sysUser.getPassword())) {
            sysUser.setPassword(EncryptionUtil.getEncryption("md5", sysUser.getPassword()));
        }
        if (StringUtils.hasText(sysUser.getUsername())) {
            Result<SysUser> sysUserResult = sysUserService.selectOne(new SysUser().setUsername(sysUser.getUsername()).setPassword(EncryptionUtil.getEncryption("md5", sysUser.getPassword())));
            if (sysUserResult.isSuccess()) {
                sysUser.setId(sysUserResult.getData().getId());
                sysUser.setPassword(EncryptionUtil.getEncryption("md5", sysUser.getNewPassword()));
            } else {
                return new Result<Integer>().setSuccess(false).setMsg("账号或密码错误");
            }
        }
        return sysUserService.updatePasswordById(sysUser);
    }

    @SysLog(value = "修改用户密码")
    @PutMapping("/update/password1")
    public Result<Integer> updatePassword1(@RequestBody SysUser sysUser) {
        if (StringUtils.hasText(sysUser.getUsername())) {
            Result<SysUser> sysUserResult = sysUserService.selectOne(new SysUser().setUsername(sysUser.getUsername()).setPassword(EncryptionUtil.getEncryption("md5", sysUser.getPassword())));
            if (sysUserResult.isSuccess()) {
                sysUser.setId(sysUserResult.getData().getId());
                sysUser.setPassword(EncryptionUtil.getEncryption("md5", sysUser.getNewPassword()));
            } else {
                return new Result<Integer>().setSuccess(false).setMsg("账号或密码错误");
            }
        }
        return sysUserService.updatePasswordById(sysUser);
    }

    /**
     * 删除
     */
    @SysLog(value = "删除用户")
    @DeleteMapping("/delete")
    public Result<Integer> delete(@RequestBody Long[] ids) {
        //删除
        List<Long> list = new ArrayList<>();
        for (Long sysUserId : ids) {
            Result resultEntity = sysUserService.deleteById(sysUserId);
            if (!resultEntity.isSuccess()) {
                list.add(sysUserId);
            }
        }
        if (list.isEmpty()) {
            return new Result().setSuccess(true);
        } else {
            return new Result().setSuccess(false).setData(list).setMsg("删除失败").setCode(SysConstant.DELETE_FAIL_CODE_RES);
        }
    }

}
